package com.xiaoerkeji.eshop.utils;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ShortcutInfo;
import android.content.pm.ShortcutManager;
import android.graphics.drawable.Icon;
import android.os.Build;
import android.util.Log;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DynamicShortcutManager
{
    private static final String TAG = "DynamicShortcutManager";

    /**
     * 创建动态快捷方式
     */
//    @TargetApi(Build.VERSION_CODES.N_MR1)
//    public static void createDynamicShortcuts(Context context)
//    {
//        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1)
//        {
//            Log.w(TAG, "Dynamic shortcuts require API level 25 or higher");
//            return;
//        }
//
//        try
//        {
//            ShortcutManager shortcutManager = context.getSystemService(ShortcutManager.class);
//
//            List<ShortcutInfo> shortcuts = new ArrayList<>();
//            shortcuts.add(createSearchShortcut(context));
//            shortcuts.add(createFavoriteShortcut(context));
//            shortcuts.add(createProfileShortcut(context));
//            shortcuts.add(createSettingsShortcut(context));
//
//            shortcutManager.setDynamicShortcuts(shortcuts);
//            Log.d(TAG, "Dynamic shortcuts created successfully");
//        } catch (Exception e)
//        {
//            Log.e(TAG, "Error creating dynamic shortcuts: " + e.getMessage());
//        }
//    }

    /**
     * 创建搜索快捷方式
     */
//    @TargetApi(Build.VERSION_CODES.N_MR1)
//    private static ShortcutInfo createSearchShortcut(Context context)
//    {
//        Intent intent = new Intent(context, SearchActivity.class);
//        intent.setAction(Intent.ACTION_VIEW);
//        intent.putExtra("source", "dynamic_shortcut");
//        intent.putExtra("type", "quick_search");
//        intent.putExtra("default_query", "热门商品");
//        intent.putExtra("category", "all");
//        intent.putExtra("timestamp", System.currentTimeMillis());
//
//        return new ShortcutInfo.Builder(context, "dynamic_search")
//                .setShortLabel("搜索")
//                .setLongLabel("快速搜索商品")
//                .setIcon(Icon.createWithResource(context, R.drawable.ic_search))
//                .setIntent(intent)
//                .build();
//    }

    /**
     * 创建收藏快捷方式
     */
//    @TargetApi(Build.VERSION_CODES.N_MR1)
//    private static ShortcutInfo createFavoriteShortcut(Context context)
//    {
//        Intent intent = new Intent(context, FavoriteActivity.class);
//        intent.setAction(Intent.ACTION_VIEW);
//        intent.putExtra("source", "dynamic_shortcut");
//        intent.putExtra("filter_type", "favorites");
//        intent.putExtra("user_id", getCurrentUserId(context));
//        intent.putExtra("sort_by", "date_added");
//
//        return new ShortcutInfo.Builder(context, "dynamic_favorite")
//                .setShortLabel("收藏")
//                .setLongLabel("查看我的收藏")
//                .setIcon(Icon.createWithResource(context, R.drawable.ic_favorite))
//                .setIntent(intent)
//                .build();
//    }

    /**
     * 创建个人资料快捷方式
     */
//    @TargetApi(Build.VERSION_CODES.N_MR1)
//    private static ShortcutInfo createProfileShortcut(Context context)
//    {
//        String userId = getCurrentUserId(context);
//
//        Intent intent = new Intent(context, ProfileActivity.class);
//        intent.setAction(Intent.ACTION_VIEW);
//        intent.putExtra("source", "dynamic_shortcut");
//        intent.putExtra("user_id", userId);
//        intent.putExtra("tab", "overview");
//        intent.putExtra("show_edit", true);
//
//        return new ShortcutInfo.Builder(context, "dynamic_profile_" + userId)
//                .setShortLabel("我的")
//                .setLongLabel("查看个人资料")
//                .setIcon(Icon.createWithResource(context, R.drawable.ic_profile))
//                .setIntent(intent)
//                .build();
//    }

    /**
     * 创建设置快捷方式
     */
//    @TargetApi(Build.VERSION_CODES.N_MR1)
//    private static ShortcutInfo createSettingsShortcut(Context context)
//    {
//        Intent intent = new Intent(context, SettingsActivity.class);
//        intent.setAction(Intent.ACTION_VIEW);
//        intent.putExtra("source", "dynamic_shortcut");
//        intent.putExtra("section", "general");
//        intent.putExtra("highlight", "notifications");
//
//        return new ShortcutInfo.Builder(context, "dynamic_settings")
//                .setShortLabel("设置")
//                .setLongLabel("应用设置")
//                .setIcon(Icon.createWithResource(context, R.drawable.ic_settings))
//                .setIntent(intent)
//                .build();
//    }

    /**
     * 创建自定义动态快捷方式
     */
    @TargetApi(Build.VERSION_CODES.N_MR1)
    public static void addCustomShortcut(Context context,
                                         String id,
                                         String shortLabel,
                                         String longLabel,
                                         int iconRes,
                                         Class<?> targetActivity,
                                         HashMap<String, Object> params)
    {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1)
        {
            return;
        }

        try
        {
            ShortcutManager shortcutManager = context.getSystemService(ShortcutManager.class);

            // 检查是否已达到最大数量
            if (shortcutManager.getDynamicShortcuts().size() >= shortcutManager.getMaxShortcutCountPerActivity())
            {
                // 移除最旧的快捷方式
                List<ShortcutInfo> currentShortcuts = new ArrayList<>(shortcutManager.getDynamicShortcuts());
                if (!currentShortcuts.isEmpty())
                {
                    currentShortcuts.remove(0);
                    shortcutManager.setDynamicShortcuts(currentShortcuts);
                }
            }

            ShortcutInfo shortcut = buildShortcutInfo(context, id, shortLabel, longLabel, iconRes, targetActivity, params);
            shortcutManager.addDynamicShortcuts(java.util.Collections.singletonList(shortcut));

            Log.d(TAG, "Custom shortcut added: " + id);

            // 立即检查是否添加成功
            List<ShortcutInfo> current = shortcutManager.getDynamicShortcuts();
            boolean success = current.stream().anyMatch(s -> s.getId().equals(id));

            Log.d(TAG, "Test shortcut creation: " + (success ? "SUCCESS" : "FAILED"));
        } catch (Exception e)
        {
            Log.e(TAG, "Error adding custom shortcut: " + e.getMessage());
        }
    }

    /**
     * 构建快捷方式信息
     */
    @TargetApi(Build.VERSION_CODES.N_MR1)
    private static ShortcutInfo buildShortcutInfo(Context context,
                                                  String id,
                                                  String shortLabel,
                                                  String longLabel,
                                                  int iconRes,
                                                  Class<?> targetActivity,
                                                  HashMap<String, Object> params)
    {
        Intent intent = new Intent(context, targetActivity);
        intent.setAction(Intent.ACTION_VIEW);
        intent.putExtra("source", "dynamic_shortcut");
        intent.putExtra("shortcut_id", id);

        // 添加自定义参数
        for (Map.Entry<String, Object> entry : params.entrySet())
        {
            String key = entry.getKey();
            Object value = entry.getValue();

            if (value instanceof String)
            {
                intent.putExtra(key, (String) value);
            } else if (value instanceof Integer)
            {
                intent.putExtra(key, (Integer) value);
            } else if (value instanceof Long)
            {
                intent.putExtra(key, (Long) value);
            } else if (value instanceof Boolean)
            {
                intent.putExtra(key, (Boolean) value);
            } else if (value instanceof Float)
            {
                intent.putExtra(key, (Float) value);
            } else if (value instanceof Double)
            {
                intent.putExtra(key, (Double) value);
            }
        }

        return new ShortcutInfo.Builder(context, id)
                .setShortLabel(shortLabel)
                .setLongLabel(longLabel)
                .setIcon(Icon.createWithResource(context, iconRes))
                .setIntent(intent)
                .build();
    }

    /**
     * 移除动态快捷方式
     */
    @TargetApi(Build.VERSION_CODES.N_MR1)
    public static void removeDynamicShortcut(Context context, String shortcutId)
    {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1)
        {
            return;
        }

        try
        {
            ShortcutManager shortcutManager = context.getSystemService(ShortcutManager.class);
            shortcutManager.removeDynamicShortcuts(java.util.Collections.singletonList(shortcutId));
            Log.d(TAG, "Shortcut removed: " + shortcutId);
        } catch (Exception e)
        {
            Log.e(TAG, "Error removing shortcut: " + e.getMessage());
        }
    }

    /**
     * 禁用快捷方式
     */
    @TargetApi(Build.VERSION_CODES.N_MR1)
    public static void disableShortcut(Context context, String shortcutId, String message)
    {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1)
        {
            return;
        }

        try
        {
            ShortcutManager shortcutManager = context.getSystemService(ShortcutManager.class);
            shortcutManager.disableShortcuts(java.util.Collections.singletonList(shortcutId), message);
            Log.d(TAG, "Shortcut disabled: " + shortcutId);
        } catch (Exception e)
        {
            Log.e(TAG, "Error disabling shortcut: " + e.getMessage());
        }
    }

    /**
     * 获取当前用户ID
     */
    private static String getCurrentUserId(Context context)
    {
        // 从 SharedPreferences 或登录信息中获取用户ID
        return "user_" + System.currentTimeMillis();
    }
}
